package com.ts.api.module.api.convert.infoflow.handler;

import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.base.StringUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.common.context.ApiContext;
import com.ts.api.common.localcache.DistrictCache;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.module.api.convert.infoflow.context.ApiInfoFlowConvertContext;
import com.ts.api.module.api.entity.ApiUserRequest;
import com.ts.api.module.api.entity.po.ApiLogPO;
import com.ts.api.module.api.entity.vo.ReqGuangDianTongVO;
import com.ts.api.module.common.entity.DistrictPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *  API投流监听器
 *
 *  @author Pan
 */
@Component
public class ApiInfoFlowHandler implements ApiInfoFlowConvertHandler {

    @Autowired
    private ApiInfoFlowConvertContext apiInfoFlowConvertContext;

    @Override
    public ApiUserRequest convert(ReqGuangDianTongVO gdtVO) {
        try {
            //  转化城市
            String city = gdtVO.getCity();
            if (ValidParam.isNotNull(city)) {
                String newCity = null;
                //   福建省-福州市-鼓楼区
                if (city.indexOf("-") != -1) {
                    newCity = StringUtils.split(city, "-")[1];
                }
                //  江苏省|扬州市|广陵区
                if (city.indexOf("|") != -1) {
                    newCity = StringUtils.split(city, "|")[1];
                }
                DistrictPO districtPO = DistrictCache.getByName(newCity);
                if (ValidParam.isNotNull(districtPO)) {
                    gdtVO.setConvertAreaName(districtPO.getName());
                    gdtVO.setConvertAreaCode(districtPO.getCode());
                }
            }

            //  添加日志属性
            ApiLogPO apiLogPO = ApiContext.LOG_OBJECT.get();
            apiLogPO.setPhoneMd5(MD5.create().digestToHex(gdtVO.getPhone()));
            //  抛出异常
            if (ValidParam.isNull(gdtVO.getConvertAreaName())) {
                apiLogPO.setAreaName(city);
                throw new ApiMsgException(ApiEnum.API_INFO_FLOW_CITY_CONVERT_ERROR.format(city));
            }
            apiLogPO.setAreaName(gdtVO.getConvertAreaName());
            apiLogPO.setAreaCode(gdtVO.getConvertAreaCode());
        } catch (ApiMsgException apiMsgException) {
            throw apiMsgException;
        } catch (Exception e) {
            throw new ApiMsgException(ApiEnum.API_INFO_FLOW_CONVERT_ERROR, e);
        }

        try {
            ApiInfoFlowConvertHandler infoFlow = apiInfoFlowConvertContext.getInfoFlow(gdtVO.getApiClientId());
            return infoFlow.convert(gdtVO);
        } catch (ApiMsgException apiMsgException) {
            throw apiMsgException;
        } catch (Exception e) {
            throw new ApiMsgException(ApiEnum.API_INFO_FLOW_CONVERT_ERROR, e);
        }
    }
}
